package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.dto.DishDto;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        String Key = "dish_"+dishDto.getCategoryId() + "_1";
        redisTemplate.delete(Key);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        log.info("page:{},pageSize:{},name:{}",page,pageSize,name);

//        0.1构建分页
        IPage<Dish> dishPage = new Page<>(page, pageSize);
//        0.2构建条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(name!=null,Dish::getName,name);
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        0.3分页查询
        dishService.page(dishPage,qw);
//        1. IPage<DishDto>
        IPage<DishDto> dishDtoPage = new Page<>(page, pageSize);
//        2. 分页基本数据：当前页、总条数...
//        对象copy（本质getter/setter）  参数：源对象、目标对象、忽略的属性
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
//        3. records中的数据:
        List<Dish> records = dishPage.getRecords();
        List<DishDto> dishDtoList = records.stream().map(item -> {//item=dish
            DishDto dishDto = new DishDto();
//           dish基本数据：name id image...
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();

            dishDto.setCategoryName(categoryName);
//                    收集成新的集合
            return dishDto;
        }).collect(Collectors.toList());

//        4. 封装好的这个数据集合要放到IPage<DishDto>  records上
        dishDtoPage.setRecords(dishDtoList);
//        0.4返回数据
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }


    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);
        dishService.deleteWithFlavor(ids);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishList = null;
        String key = "dish_" + dish.getCategoryId() + "_" +dish.getStatus();
        dishList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishList != null){
            return R.success(dishList);
        }
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {//item   -  dish
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);//普通字段copy

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);//把口味放到Flavors

            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

    @PostMapping("/status/{status}")
    public R status(@RequestParam List<Long> ids,@PathVariable Integer status){
        log.info("ids:{}",ids);
        List<Dish> dishDtolist = ids.stream().map(item->{
            Dish dish = new Dish();
            dish.setId(item);
            dish.setStatus(status);
            return dish;
        }).collect(Collectors.toList());
        dishService.updateBatchById(dishDtolist);
        return R.success("修改成功");
    }

}